/*
Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
*/

#if 0
/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> res;
        multimap<int, int> interval_map;
        if (!intervals.size()) return res;
        // insert all intervals into map, sort based on left edge
        for (auto it = intervals.begin(); it != intervals.end(); it++) {
            interval_map.insert(pair<int, int>((*it).start, (*it).end));
        }
        Interval cur, next;
        auto it = interval_map.begin();
        cur.start = (*it).first; cur.end = (*it).second;
        // scan the interval map and merge intervals
        for (it++; it != interval_map.end(); it++, cur=next) {
            next.start = (*it).first; next.end =  (*it).second;
            while(cur.end >= next.start) {
                cur.end = (cur.end >= next.end)?cur.end:next.end;
                if (++it == interval_map.end()) break;
                next.start = (*it).first; next.end =  (*it).second;
            }
            if (it == interval_map.end()) break;
            res.push_back(cur);
        }
        res.push_back(cur);  // add the last one
        return res;
    }
};
#endif

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    struct sortInterval {
        bool operator() (Interval i1, Interval i2) {
            return (i1.start < i2.start);
        }
    };
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> res;
        if (!intervals.size()) return res;
        sort(intervals.begin(), intervals.end(), sortInterval());
        res.push_back(intervals[0]);
        for (int i = 1; i < intervals.size(); i++) {
            // merge current interval with tail of result
            Interval &cur = intervals[i];
            Interval &back = res.back();
            if (cur.start <= back.end) back.end = (cur.end > back.end)?cur.end:back.end;
            else res.push_back(cur);
        }
        return res;
    }
};
